package com.zcq.dm.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.zcq.dm.masking.DMInfo;
import com.zcq.dm.masking.IDataMasking;
import com.zcq.dm.utils.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * 脱敏转换器
 */
public class DMConverter implements Converter<String> {
    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return null;
    }

    @Override
    public WriteCellData<String> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if(StringUtils.isBlank(value)){
            return new WriteCellData(value);
        }

        Field field = contentProperty.getField();
        DMInfo dMInfo = field.getAnnotation(DMInfo.class);
        if(dMInfo == null){
            return new WriteCellData(value);
        }

        IDataMasking dataMasking = SpringContextUtil.getBean(IDataMasking.class);
        if(dataMasking == null){
            return new WriteCellData(value);
        }
        //是否命中权限脱敏白名单，命中则不脱敏
        if(dataMasking.isHitWhite(dMInfo.type())){
            return new WriteCellData(value);
        }

        return new WriteCellData(dMInfo.type().getDsMethod().apply(value));
    }

}
